package org.szgb.console.sys.line.web;

import cn.hutool.http.HttpStatus;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.szgb.console.sys.line.entity.SysLineLocation;
import org.szgb.console.sys.line.entity.SysLineLocationSystem;
import org.szgb.console.sys.line.entity.SysLineLocationSystemEquipment;
import org.szgb.console.sys.line.service.SysLineLocationService;
import org.szgb.console.sys.line.service.SysLineLocationSystemEquipmentService;
import org.szgb.console.sys.line.service.SysLineLocationSystemService;
import org.szgb.console.sys.user.entity.SysUser;
import org.szgb.console.utils.PageView;
import org.szgb.console.utils.TokenUtil;
import org.szgb.core.base.entity.GetIdDto;
import org.szgb.core.utils.AjaxJson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping(value = "/sys/line/location")
@Tag(name = "线路站点管理", description = "线路站点管理模块")
public class SysLineLocationController {
    private final SysLineLocationService sysLineLocationService;
    private final SysLineLocationSystemService sysLineLocationSystemService;
    private final SysLineLocationSystemEquipmentService sysLineLocationSystemEquipmentService;

    @Autowired
    public SysLineLocationController(SysLineLocationService sysLineLocationService, SysLineLocationSystemService sysLineLocationSystemService, SysLineLocationSystemEquipmentService sysLineLocationSystemEquipmentService) {
        this.sysLineLocationService = sysLineLocationService;
        this.sysLineLocationSystemService = sysLineLocationSystemService;
        this.sysLineLocationSystemEquipmentService = sysLineLocationSystemEquipmentService;
    }


    @Operation(summary = "获取线路站点信息", description = "根据查询参数获取线路站点信息，支持分页查询。使用id获取更详细的信息。")
    @PostMapping("/get")
    public AjaxJson get(@RequestBody(required = false) SysLineLocation.SysLineLocationFindDto findDto, HttpServletRequest request, HttpServletResponse response) {
        if (findDto == null) {
            findDto = new SysLineLocation.SysLineLocationFindDto();
        }
        // 创建一个PageView对象，用于分页显示
        PageView<SysLineLocation.SysLineLocationView> pageView = new PageView<>();
        SysLineLocation sysLineLocation = findDto.toSysLineLocation();
        // 如果实体对象的ID不为空，则直接调用get方法获取单个实体对象
        if (sysLineLocation != null && sysLineLocation.getId() != null && !sysLineLocation.getId().isEmpty()) {
            SysLineLocation lineLocation = sysLineLocationService.get(sysLineLocation.getId());
            // 如果实体对象为空，则返回错误响应
            if (lineLocation == null) {
                return AjaxJson.error("数据不存在", HttpStatus.HTTP_NOT_FOUND, request, response);
            }
            // 返回成功的响应，并将实体对象放入响应中
            return AjaxJson.success(request, response).put("sysLineLocation", lineLocation.toSysLineLocationView());
        } else {
            // 设置Page对象的列表属性，包含根据实体对象查询到的数据
            pageView.setList(SysLineLocation.SysLineLocationView.getViewListFromList(sysLineLocationService.findList(sysLineLocation)));
            // 设置Page对象的总记录数属性，用于分页显示
            pageView.setCount(sysLineLocationService.getCount(sysLineLocation));
            // 创建一个成功的AjaxJson对象，并放入Page对象，以便于前端展示
            return AjaxJson.success(request, response).put("page", pageView);
        }
    }

    @Operation(summary = "获取线路站点树表信息", description = "根据查询参数获取线路站点树表信息，必须填写id。")
    @PostMapping("/getTree")
    public AjaxJson getTree(@RequestBody(required = false) GetIdDto getIdDto, HttpServletRequest request, HttpServletResponse response) {
        // 获取线路站点对象
        SysLineLocation sysLineLocation = sysLineLocationService.get(getIdDto.getId());
        SysLineLocationSystem sysLineLocationSystem = new SysLineLocationSystem();
        sysLineLocationSystem.setSysLineLocation(sysLineLocation);
        // 获取线路站点系统列表
        List<SysLineLocationSystem> SysLineLocationSystemList = sysLineLocationSystemService.findList(sysLineLocationSystem);
        String[] array = SysLineLocationSystemList.stream().map(SysLineLocationSystem::getId).toArray(String[]::new);
        // 获取线路站点系统设备列表
        List<SysLineLocationSystemEquipment> sysLineLocationSystemEquipmentList = sysLineLocationSystemEquipmentService.getByLocationSystemIdArray(array);
        // 转换为map表
        Map<String, List<SysLineLocationSystemEquipment>> equipmentMap = new HashMap<>();
        for (String id : array) {
            equipmentMap.put(id, new ArrayList<>());
        }
        sysLineLocationSystemEquipmentList.forEach(sysLineLocationSystemEquipment -> equipmentMap.get(sysLineLocationSystemEquipment.getSysLineLocationSystem().getId()).add(sysLineLocationSystemEquipment));
        List<SysLineLocationSystem.SysLineLocationSystemTreeView> sysLineLocationSystemTreeViewList = new ArrayList<>();
        // 填充设备表进系统表
        SysLineLocationSystemList.forEach(lineLocationSystem -> {
            sysLineLocationSystemTreeViewList.add(
                    new SysLineLocationSystem.SysLineLocationSystemTreeView(lineLocationSystem, SysLineLocationSystemEquipment.SysLineLocationSystemEquipmentTreeView.getViewListFromList(equipmentMap.get(lineLocationSystem.getId()))));
        });
        return AjaxJson.success(request, response).put("tree", new SysLineLocation.SysLineLocationTreeView(sysLineLocation, sysLineLocationSystemTreeViewList));
    }

    @PostMapping("/save")
    @Operation(summary = "保存线路站点", description = "新增或更改线路站点信息。")
    public AjaxJson save(@RequestBody SysLineLocation.SysLineLocationSaveDto sysLineLocationSaveDto, HttpServletRequest request, HttpServletResponse response) {
        if (sysLineLocationSaveDto == null) {
            return AjaxJson.error("参数错误", HttpStatus.HTTP_BAD_REQUEST, request, response);
        }
        SysLineLocation sysLineLocation = sysLineLocationSaveDto.toSysLineLocation();
        // 设置实体对象的更新者为当前用户
        sysLineLocation.setUpdatedBy(new SysUser(TokenUtil.getUid(request)));
        // 调用服务层的save方法，尝试保存或更新实体对象，返回保存结果的Map
        sysLineLocationService.save(sysLineLocation);
        // 根据保存结果返回相应的AjaxJson对象
        return AjaxJson.success("保存成功", request, response).put("sysLineLocation", sysLineLocation.toSysLineLocationView());
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除线路站点", description = "根据ID删除线路站点信息。", parameters = {@Parameter(name = "ids", description = "线路ID列表，多个ID用英文逗号分隔。")})
    public AjaxJson delete(@RequestParam String ids, HttpServletRequest request, HttpServletResponse response) {
        // 检查ID参数是否为空，为空则返回错误响应
        if (ids == null) {
            return AjaxJson.error("参数错误", HttpStatus.HTTP_BAD_REQUEST, request, response);
        }
        // 调用服务层方法，执行删除操作
        sysLineLocationService.delete(ids);
        // 返回成功响应
        return AjaxJson.success(request, response);
    }
}
